package com.yang.news.interceptor;

import cn.hutool.core.net.Ipv4Util;
import com.alibaba.fastjson.JSON;
import com.yang.news.enums.CacheKeyEnums;
import com.yang.news.model.result.CommonErrorCode;
import com.yang.news.model.result.ResultModel;
import com.yang.news.util.IPUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import sun.net.util.IPAddressUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * 限制每个Ip的访问频率
 *
 * @author: Billyang
 * @date: 2024/9/15 15:45
 */
@Slf4j
public class IpControlFrequencyInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    private String key;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String remoteIP = IPUtil.getRemoteIP(request);
        log.info("IpControlFrequencyInterceptor remoteIp:{}", remoteIP);
        key = CacheKeyEnums.REMOTE_IP.getKey(remoteIP);
        Integer val = (Integer) redisTemplate.opsForValue().get(key);
        if (val == null) {
            redisTemplate.opsForValue().set(key,0,60, TimeUnit.SECONDS);
            return true;
        }
        if (val >= Integer.valueOf(CacheKeyEnums.REMOTE_IP.getValue())) {
            log.info("IpControlFrequencyInterceptor remoteIp:{} is over limit,val:{}", remoteIP, val);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(ResultModel.unSuccess(CommonErrorCode.IP_FREQUENCY_LIMIT)));
            return false;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        Object val = redisTemplate.opsForValue().get(key);
        if(val == null){
            redisTemplate.opsForValue().set(key,1,60, TimeUnit.SECONDS);
        }else{
            redisTemplate.opsForValue().increment(key);
        }
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
